<template>
  <n-menu
    class="global-sider h-full"
    v-model:expanded-keys="expandedKeys"
    :value="activeKey"
    :options="routerStore.menus"
    :collapsed-icon-size="22"
    :collapsed-width="64"
    :indent="18"
    @update:value="handleMenuSelect"
  >
  </n-menu>
</template>

<script lang="tsx" setup>
import type { MenuOption } from "naive-ui";
import { useRouterStore } from "@/store";
import { getActiveKeyOfMenus } from "./common";
import type { RouteLocationRaw } from "vue-router";

const routerStore = useRouterStore();
const route = useRoute();
const router = useRouter();
const expandedKeys = ref<string[]>([]);
const activeKey = computed(
  () => (route.meta?.activeMenu || route.name) as string
);

const routerPush = (to: RouteLocationRaw, newTab = false) => {
  if (newTab) {
    const routerData = router.resolve(to);
    window.open(routerData.href, "_blank");
    return Promise.resolve();
  }
  return router.push(to);
};

const handleMenuSelect = (_key: string, item: MenuOption) => {
  const menuItem = item as Sys.Menu;
  routerPush(menuItem.path, menuItem.newTab);
};

watch(
  () => route.name,
  async () => {
    expandedKeys.value = getActiveKeyOfMenus(
      activeKey.value,
      routerStore.menus!
    );
  },
  { immediate: true }
);
</script>
<style scoped>
.global-sider {
  box-shadow: 2px 0 8px 0 rgb(29 35 41 / 5%);
}
</style>
